/**
 * Created by dale on 2017/10/25.
 */
var sMobileId = null;
$(document).ready(function () {
    // var remember = xhTool.getCookie('trust') == 'true' ? true : false;
    $('#remember').switchbutton({
        checked: remember,
        onChange: function(checked){
            remember=checked;
        }
    });

    // var trust = xhTool.getCookie('trust') == 'true' ? true : false;
    $('#trust').switchbutton({
        checked: trust,
        onChange: function(checked){
            trust = checked;
        }
    });
    // sMobileId = '865124039929957';
    // JSObjectHandle.setUUID('865124039929957');

    $('#account').textbox('textbox').bind('change', function(e){
        var  val = $(this).val();
        checkValid(val);
    });

    // var account = $('#account').textbox('getValue');
    // if(account) { //添加admin显示
    //     checkValid(account);
    // }

    try {

        chageColor('#0066cc');
        addGuesture();
        getShellInfo();
        getUUID();

    }
    catch (e) {
        // sendErrorMsg(e)
    }

    $('#phone').numberbox({
        onClickButton:function () {  //按钮点击事件
            var val = $('#phone').numberbox('getValue');
            var phoneReg = /^1[0-9]{10}$/;
            var account=$('#account').textbox('getValue');
            if(phoneReg.test(val)){
                $.ajax({
                    url:baseUrl+'index/getLoginSmsCode',
                    data:{account:account,phone:val},
                    type:'post',
                    dataType:'json',
                    success:function (res) {
                        console.log(res);
                        sendSuccessMsg(res.msg);
                    },
                    error:function (res) {
                        var result = res.responseJSON || res.responseText;
                        sendErrorMsg(result.error);
                    }
                });
            }else {
                sendErrorMsg('手机号格式不匹配');
            }
        }
    });




    $('#login').click(function () {

        var account=$('#account').textbox('getValue');
        var password=$('#password').passwordbox('getValue');
        var smsCode = $('#smsCode').numberbox('getValue');


        if (!account||!password) {
            sendErrorMsg('用户名或密码为空');
            return false;
        }
        if (trust && !sMobileId) {
            swal({
                title:'提示',
                text: '未获取到设备号，无法信任设备',
                type:'info',
                confirmButtonText:'确定',
                preConfirm: function() {
                    return new Promise(function (resolve, reject) {
                        $('#login').linkbutton({
                            text:'登录中...',
                            disabled:true
                        });
                        $.ajax({
                            url:baseUrl+'mobile/index/doLogin',
                            data:{account:account,password:password,smsCode:smsCode,remember:remember,auto:true,trust:trust,sMobileId:sMobileId},
                            type:'POST',
                            success:function (data) {
                                window.location.reload();
                            },
                            error:function (res) {
                                var result = res.responseJSON || res.responseText;
                                if(typeof result === 'string'){
                                    sendErrorMsg(result);
                                }
                                if(result.error){
                                    sendErrorMsg(result.error);
                                }

                            },
                            complete:function (res) {
                                $('#login').linkbutton({
                                    text:'登录',
                                    disabled:false
                                });
                            }
                        });
                    });
                }
            }).then(function (accept) {}, function(dismiss) {});
        } else  {
            $('#login').linkbutton({
                text:'登录中...',
                disabled:true
            });
            $.ajax({
                url:baseUrl+'mobile/index/doLogin',
                data:{account:account,password:password,smsCode:smsCode,remember:remember,auto:true,trust:trust,sMobileId:sMobileId},
                type:'POST',
                success:function (data) {
                    window.location.reload();
                },
                error:function (res) {
                    var result = res.responseJSON || res.responseText;
                    if(typeof result === 'string'){
                        sendErrorMsg(result);
                    }
                    if(result.error){
                        sendErrorMsg(result.error);
                    }

                },
                complete:function (res) {
                    $('#login').linkbutton({
                        text:'登录',
                        disabled:false
                    });
                }
            });
        }


    });



});


function checkValid(account) {
    $.ajax({
        url:baseUrl+'mobile/index/checkNeedValid',
        data:{account:account,sMobileId:sMobileId,trust:trust},
        type:'post',
        dataType:'json',
        success:function (data) {
            // sendSuccessMsg(data);
            $('#sendMsg').show();
        },
        error:function (res) {
            // sendErrorMsg(res);
            $('#sendMsg').hide();
        }
    });
}


function sendErrorMsg($msg) {
    swal({title:'错误',text: $msg,type:'error',confirmButtonText:'确定'});
}

function sendSuccessMsg($msg) {
    swal({title:'成功',text: $msg,type:'success',confirmButtonText:'确定'});
}

/**
 * 判断android ios 设备
 * create by dale 20180122
 */
function identifyDev() {
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    console.log(isAndroid);
    console.log(isiOS);
    if(isAndroid){
        return 1;
    }else if(isiOS) {
        return  2;
    }else {
        return 3;
    }
}

/**
 * 改变颜色
 * create by dale 20180122
 */
function chageColor(color) {
    var flag = identifyDev();
    if(flag == 1){
        window.XueHai.setBarColor(color);
    }else if(flag == 2){
        window.webkit.messageHandlers.setBarColor.postMessage({color:color});
    }else {
        // sendErrorMsg('找不到设备类型');
    }
}


function addGuesture() {
    var flag = identifyDev();
    if(flag == 1){
        window.XueHai.addGuesture();
    }else if(flag == 2){
        window.webkit.messageHandlers.addGuesture.postMessage(null);
    }else {
        // sendErrorMsg('找不到设备类型');
    }
}

/**
 * 获取uuId
 *
 * create by dale 20180809
 */
function getUUID() {
    var flag = identifyDev();
    if(flag == 1){
        window.XueHai.getUUID();
    }else if(flag == 2){
        window.webkit.messageHandlers.getUUID.postMessage(null);
    }else {
        // sMobileId = '865124039929957';
        // JSObjectHandle.setUUID('865124039929957');
        // sendErrorMsg('找不到设备类型');
    }
}

function getMacAddress() {
    var flag = identifyDev();
    if(flag == 1){
        window.XueHai.getMacAddress();
    }else if(flag == 2){
        window.webkit.messageHandlers.getMacAddress.postMessage(null);
    }else {
        // sendErrorMsg('找不到设备类型');
    }
}


function getShellInfo() {
    var flag = identifyDev();
    if(flag == 1){
        window.XueHai.getAppInfo();
    }else if(flag == 2){
        window.webkit.messageHandlers.getInfoDictionary.postMessage(null);
    }else {
        // sendErrorMsg('找不到设备类型');
    }
}


var JSObjectHandle = {
    setUUID:function (uuid) {
            sMobileId = uuid;
            var account = $('#account').textbox('getValue');
            if(account) { //添加admin显示
                checkValid(account);
            }
        // sendSuccessMsg(sMobileId);
    },
    setMacAddress :function (address) {
        sendSuccessMsg(address);
    },
    setAppInfo:function (info) { //只走android
        // sendSuccessMsg(info);
        if (info) {
            // sendSuccessMsg(info);
            info = $.parseJSON(info);

            $('#footer').append('<p><font class="pull-left" color="gray">版本名称：&nbsp;&nbsp;'+info['versionName']+'&nbsp;&nbsp;</font><font class="pull-right" color="gray">版本号:&nbsp;&nbsp;'+info['versionCode']+'&nbsp;&nbsp;</font></p>\n');
            $.ajax({
                url:baseUrl+'mobile/index/checkVersion',
                data: info,
                type:'post',
                dataType:'json',
                success:function (data) {
                    // sendSuccessMsg(JSON.stringify(data));
                    if (data['code'] == 201) {
                        window.top.swal({
                            titleText: data['msg'],
                            html:'<input id="url" name="url"  class="form-control" value="'+data['url']+'"    readonly/><br>' +
                            '<button class="copyBtn  btn btn-primary"  data-clipboard-action="copy" data-clipboard-target="#url">点击复制</button>',
                            showCancelButton: false,
                            showConfirmButton:false,
                            // confirmButtonText: '确认',
                            // showLoaderOnConfirm: true,
                            allowOutsideClick: true,
                            preConfirm: function () {
                                return new Promise(function (resolve, reject) {
                                    var url = $('#url').val();
                                    if (!url) {
                                        reject('名称必填！');
                                    } else {
                                        resolve(url);
                                    }
                                })
                            },
                            onOpen:function () {
                                var clipboard = new ClipboardJS('.copyBtn');
                                clipboard.on('success', function(e) {
                                    alert(e.text+'已复制到黏贴板');
                                });
                                clipboard.on('error', function(e) {
                                    alert(e);
                                });

                            }
                        }).then(function (url) {
                        }, function(dismiss) {});
                    }
                },
                error:function (res) {
                    sendSuccessMsg(JSON.stringify(res));
                    // $('#sendMsg').hide();
                }
            });
        }
    },
    setInfoDictionary:function (info) { //只走ios
        // alert(info);
        // return false;
        if (info) {
            var infoObj = $.parseJSON(info);
            var packageName = infoObj['CFBundleIdentifier'];
            var versionName = infoObj['CFBundleShortVersionString'];
            var versionCode = infoObj['CFBundleInfoDictionaryVersion'];
            $('#footer').append('<p><font class="pull-left" color="gray">版本名称：&nbsp;&nbsp;'+versionName+'&nbsp;&nbsp;</font><font class="pull-right" color="gray">版本号:&nbsp;&nbsp;'+versionCode+'&nbsp;&nbsp;</font></p>\n');
            $.ajax({
                url:baseUrl+'mobile/index/checkVersion',
                data: {name:infoObj['CFBundleName'],packageName:packageName,versionName:versionName,versionCode:versionCode,isIos:'true'},
                type:'post',
                dataType:'json',
                success:function (data) {
                    // sendSuccessMsg(JSON.stringify(data));
                    if (data['code'] == 201) {
                        // location.href = data['url'];
                        window.top.swal({
                            titleText: data['msg'],
                            html:'<input id="url" name="url"  class="form-control" value="'+data['url']+'"    readonly/><br>' +
                            '<button class="copyBtn  btn btn-primary"  data-clipboard-action="copy" data-clipboard-target="#url">点击复制</button>',
                            showCancelButton: false,
                            showConfirmButton:false,
                            // confirmButtonText: '确认',
                            // showLoaderOnConfirm: true,
                            allowOutsideClick: true,
                            preConfirm: function () {
                                return new Promise(function (resolve, reject) {
                                    var url = $('#url').val();
                                    if (!url) {
                                        reject('名称必填！');
                                    } else {
                                        resolve(url);
                                    }
                                })
                            },
                            onOpen:function () {
                                var clipboard = new ClipboardJS('.copyBtn');
                                clipboard.on('success', function(e) {
                                    alert(e.text+'已复制到黏贴板');
                                });
                                clipboard.on('error', function(e) {
                                    alert(e);
                                });

                            }
                        }).then(function (url) {
                        }, function(dismiss) {});
                    }
                },
                error:function (res) {
                    sendSuccessMsg(JSON.stringify(res));
                    // $('#sendMsg').hide();
                }
            });
        }
    }
};